package com.cskaoyan.shiro;

import com.cskaoyan.bean.pojo.MarketUser;
import com.cskaoyan.bean.pojo.MarketUserExample;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.utils.Password2Message;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 创建日期: 2022/04/09 12:51
 *
 * @author HanWeiqi
 */
@Component
public class WxRealm extends AuthorizingRealm {

    @Autowired
    MarketUserMapper marketUserMapper;

    //获得认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        MallToken token = (MallToken) authenticationToken;
        String username = token.getUsername();

        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria criteria = marketUserExample.createCriteria();
        if(username!=null && !"".equals(username)) {
            criteria.andUsernameLike(username);
        }
        // 由于用户名唯一，所以如果输入用户名存在，那么这个list只有一条数据
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(marketUserExample);
        // 没有查询到这个用户名，直接返回null
        if (marketUsers == null || marketUsers.size() == 0) {
            return null;
        }
        MarketUser marketUser = marketUsers.get(0);

        // 得到查询出的用户的密码
        String password =  marketUser.getPassword();

        return new SimpleAuthenticationInfo(marketUser, password, this.getName());
    }

    //获得授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权方法中可以拿到用户信息
        MarketUser primaryPrincipal = (MarketUser) principalCollection.getPrimaryPrincipal();
        return null;
    }
}

